package com.gzhryc.common.data;

import java.util.ArrayList;
import java.util.List;

public class TreeUtils {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <T extends ITreeEntity> List<T> byTree(List<T> data){
		 List result = null;
		 if(data != null && data.size() > 0) {
			 result = new ArrayList();
			 for(T entity : data){
				 if(entity.getParentId() == null) {
					  next(entity,data);
					  result.add(entity);
				 }
			 }
		 }
        return result;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	private static <T extends ITreeEntity> void next(T parent,List<T> data){
        for(T entity : data) {
        	if(entity.getParentId() != null && parent.getId().equals(entity.getParentId())){
        		if(parent.getChildren() == null) {
        			parent.setChildren(new ArrayList<>());
        		}
                parent.getChildren().add(entity);
                next(entity,data);
            }
        }
    }
    
    public static <T extends ITree<?>,E extends ITreeEntity<E,?>> List<E> byTree(List<T> data,ConvertListen<T,E> convertListen){
		 List<E> result = null;
		 if(data != null && data.size() > 0) {
			 result = new ArrayList<E>();
			 for(T item : data){
				 if(item.getParentId() == null || "0".equals(item.getParentId().toString())) {
					 E entity = convertListen.change(null,item);
					 next(entity,item,data,convertListen);
					 result.add(entity);
				 }
			 }
		 }
		 return result;
   }
    
	private static <T extends ITree<?>,E extends ITreeEntity<E,?>> void next(E parentEntity,T parent,List<T> data,ConvertListen<T,E> convertListen){
        for(T item : data) {
        	if(item.getParentId() != null && parent.getId().equals(item.getParentId())){
        		if(parentEntity.getChildren() == null) {
        			parentEntity.setChildren(new ArrayList<E>());
        		}
        		E entity = convertListen.change(parent,item);
        		parentEntity.getChildren().add(entity);
                next(entity,item,data,convertListen);
            }
        }
    }
    
    public static <T extends ITree<?>,E extends ITreeEntity<E,?>> List<E> byTree(Object rootId,List<T> data,ConvertListen<T,E> convertListen){
		 List<E> result = null;
		 if(data != null && data.size() > 0) {
			 result = new ArrayList<E>();
			 for(T item : data){
				 if(rootId != null && item.getId().equals(rootId)) {
					 E entity = convertListen.change(null,item);
					 next(entity,item,data,convertListen);
					 result.add(entity);
				 }
			 }
		 }
		 return result;
   }
    
   public static interface ConvertListen<T,E> {
	   
		public E change(T parent,T obj);
    	
   }
}
